<template>
    <el-dialog class="dialog" :title="$t('avatar')" :model-value="showCropper"  width="600px"
        @closed="resetCropper">
        <el-upload :show-file-list="false" :on-change="handleFileChange" :before-upload="beforeUpload" accept="image/*" name="file">
            <el-button>{{ $t('upload') }}</el-button>
        </el-upload>
        <div v-if="imageUrl2" style="margin: 20px 0;">
            <cropper ref="cropperRef" :src="imageUrl2" :aspect-ratio="1" style="height: 400px; width: 100%;margin: initial !important;" />
        </div>
        <span v-show="imageUrl2" slot="footer" class="dialog-footer">
            <el-button @click="getCroppedImage(false)">{{ $t('cancellation') }}</el-button>
            <el-button type="primary" @click="getCroppedImage">{{ $t('confirm') }}</el-button>
        </span>
    </el-dialog>
</template>

<script setup>
import Cropper from 'vue-cropperjs';
import 'cropperjs/dist/cropper.css';
import { ref,toRefs,watch } from 'vue';

const props = defineProps(['showCropper','changeImg'])
let {showCropper,changeImg} = toRefs(props)
console.log(showCropper.value,'showCropper');
watch(showCropper,(val)=>{
    console.log(val,'val');
})
const imageUrl = ref('');
const imageUrl2 = ref(null);
const cropperRef = ref(null);

const handleFileChange = (file) => {
    console.log(file,'file');
    const reader = new FileReader();
    reader.onload = (e) => {
        console.log(e,'eeeeeeee');
        imageUrl2.value = e.target.result;
    };
    reader.readAsDataURL(file.raw);

    // const formData = new FormData()
    // formData.append('file', file.raw)
    // imageUrl.value = formData
    // console.log('formData', formData.get('file'));
};

const beforeUpload = (file) => {
    console.log(file);
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
        changeImg.value(null,false)
        ElMessage.error('只能上传图片!');
    }
    
    return isImage;
};

const getCroppedImage = (type) => {
    if(!type){
        changeImg.value('',false)
        return
    }
    cropperRef.value.getCroppedCanvas().toBlob((blob) => {
        const formData = new FormData()
        console.log('blob', blob);
        
        formData.append('file', blob)
        imageUrl.value = formData
        console.log('formData', formData.get('file'));
        changeImg.value(imageUrl.value,true)
    });
};

const resetCropper = () => {
    console.log(123);
    getCroppedImage(false)
    imageUrl.value = null;
    imageUrl2.value = null;
};


</script>

<style scoped>
.dialog-footer {
    text-align: right;
}
</style>